const api = require('../../../api/store_api');
import { toast, log, err } from '../../../utils/wxapi';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    size: 10,
    list: [],
  },
  onLoad() {
    this.paylist();
  },
  async paylist() {
    try {
      const res = await api.payList({ status: 'NORMAL' });
      if (res.respCode === 200) {
        const list = JSON.parse(res.source);
        log(list);
        this.setData({ list });
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  pay(e) {
    try {
      const { amount, mktid, type } = e.currentTarget.dataset;
      const payType = 'POINT_RECHARGE';
      const ordersId = 0;
      const processPayment = async paydata => {
        const resp = await api.pay(paydata);
        if (resp.respCode === 200) {
          const payment = JSON.parse(resp.source);
          wx.requestPayment({
            ...payment,
            success: () => {
              toast('支付成功');
            },
            fail: () => {
              toast('支付失败');
            },
          });
        } else {
          toast(resp.msg);
        }
      };

      if (type === 'RATIO') {
        wx.showModal({
          title: '请输入充值金额',
          editable: true,
          complete: async res => {
            if (res.confirm) {
              if (!res.content) {
                const data = {
                  payType,
                  amount: res.content,
                  ordersId,
                  mktId: mktid,
                };
                processPayment(data);
              } else {
                toast('请输入充值金额');
              }
            }
          },
        });
      } else {
        wx.showModal({
          title: '您确定充值一下金额吗？',
          content: '充值金额' + amount,
          complete: async res => {
            if (res.confirm) {
              const data = {
                payType,
                amount,
                ordersId,
                mktId: mktid,
              };
              processPayment(data);
            }
          },
        });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  togood() {
    wx.switchTab({ url: '/pages/good/good' });
  },
});
